package com.ys.data.auth.filter;

import com.alibaba.fastjson.JSONArray;
import com.common.base.BaseEnum;
import com.common.util.FastJsonUtils;
import com.common.util.JWTUtils;
import com.common.util.RedisUtil;
import com.common.vo.RoleVo;
import com.ys.data.auth.entity.Role;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
* @version: V1.0
* @author: szw
* @className: JwtFilter
* @packageName: JwtFilter
* @description:  jwt 过滤器暂时注释
* @data: 2021-1-19 
**/ 
@Slf4j
//@Component
public class JwtFilter implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("经过了拦截器");
        final String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            final String token = authHeader.substring(7);
            Claims claims = JWTUtils.parseJWT(token);
            if (claims != null) {
                String redisData =  redisUtil.get(BaseEnum.INIT_ROLE_REDIS_KEY.getCode());
                List<Role> redisRoleList = FastJsonUtils.getArrayJson(redisData,Role.class);
                if (CollectionUtils.isEmpty(redisRoleList)){
                    log.error("Redis获取角色信息为空");
                }
                List<Role> roleList = FastJsonUtils.getArrayJson(JSONArray.toJSONString(redisRoleList),Role.class);
                roleList.forEach(item->{
                    if(BaseEnum.ADMIN_ROLE.equals(claims.get("roleCd"))){//如果是管理员
                        request.setAttribute("admin_claims", claims);
                    }
                    if(BaseEnum.DEFAULT_ROLE.equals(claims.get("roleCd"))){//如果是用户
                        request.setAttribute("user_claims", claims);
                    }
                });

            }
        }
    }
}
